// utils/wechat.js
import {getWechatConfig} from '@/api/wechat'
import wx from 'weixin-js-sdk'

export const initWechatSDK = async (options = {}) => {
    try {
        // 默认配置
        const defaultOptions = {
            debug: process.env.NODE_ENV !== 'production',
            jsApiList: [
                'updateAppMessageShareData',
                'updateTimelineShareData'
            ],
            shareConfig: {
                title: document.title,
                desc: '新华新消费',
                link: window.location.href,
                imgUrl: 'https://xinxf.oss-cn-hangzhou.aliyuncs.com/resources/logo.png'
            }
        }

        // 合并配置
        const finalOptions = { ...defaultOptions, ...options }

        // 获取当前页面URL（去掉hash部分）
        const url = window.location.href.split('#')[0]

        // 从后端获取签名配置
        const { data } = await getWechatConfig({ url})
        let config = data
        // 初始化微信配置
        wx.config({
            debug: finalOptions.debug,
            appId: config.appid,
            timestamp: config.timestamp,
            nonceStr: config.nonceStr,
            signature: config.signature,
            jsApiList: finalOptions.jsApiList
        })

        // 返回Promise以便链式调用
        return new Promise((resolve, reject) => {
            wx.ready(() => {
                // 设置分享内容
                if (finalOptions.shareConfig) {
                    wx.updateAppMessageShareData(finalOptions.shareConfig)
                    wx.updateTimelineShareData({
                        title: finalOptions.shareConfig.title,
                        link: finalOptions.shareConfig.link,
                        imgUrl: finalOptions.shareConfig.imgUrl
                    })
                }
                resolve(wx)
            })

            wx.error(err => {
                console.log('微信配置错误:', err)
                reject(err)
            })
        })

    } catch (error) {
        console.error('初始化微信SDK失败:', error)
        throw error
    }
}